package cn.educate.service;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class RealTimeChatBotServer {
	private ServerSocket serverSocket;
	private List<Socket> clients;

	public RealTimeChatBotServer(int port) throws IOException {
		serverSocket = new ServerSocket(port);
		clients = new ArrayList<>();
		System.out.println("Server started on port " + port);
	}

	public void start() {
		while (true) {
			try {
				Socket clientSocket = serverSocket.accept();
				System.out.println("New client connected: " + clientSocket.getInetAddress());
				clients.add(clientSocket);
				new ClientHandler(clientSocket).start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private class ClientHandler extends Thread {
		private Socket clientSocket;
		private BufferedReader in;
		private PrintWriter out;

		public ClientHandler(Socket socket) {
			this.clientSocket = socket;
			try {
				in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
				out = new PrintWriter(clientSocket.getOutputStream(), true);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {
			String inputLine;
			try {
				while ((inputLine = in.readLine()) != null) {
					System.out.println("Received message from client: " + inputLine);
					String response = processMessage(inputLine);
					out.println(response);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					clientSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		private String processMessage(String message) {
			// 这里可以添加实际的聊天机器人逻辑
			// 示例：简单的回显消息
			return "Echo: " + message;
		}
	}

	public static void main(String[] args) {
		try {
			RealTimeChatBotServer server = new RealTimeChatBotServer(12345);
			server.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}